package com.celesea.workflow.component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.celesea.framework.api.SuccessTip;
import com.celesea.framework.api.Tip;
import com.celesea.framework.authority.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author JackYuan
 * @create 2017-11-21 23:02
 */
@Component
public class AuthService {
    @Autowired
    private AuthProperties authProperties;

    public List<User> getUsersByDeptAndPosition(String deptId, String positionCode) {
        Map<String, Object> uriVariables = new HashMap<String, Object>();
        uriVariables.put("deptId", deptId);
        uriVariables.put("positionCode", positionCode);
        Tip result = RestTemplateUtils.get(authProperties.getUsersByDeptAndPosition(), uriVariables, Tip.class);
        Assert.isTrue(result.getCode() == SuccessTip.CODE, result.getMessage());
        Object content = result.getContent();
        if (content == null) {
            return null;
        }
        return ((List<JSONObject>) content).stream()
                .map(item -> JSON.toJavaObject(item, User.class)).collect(Collectors.toList());
    }

    public User getUserById(String userId) {
        Map<String, Object> uriVariables = new HashMap<String, Object>();
        uriVariables.put("userId", userId);
        Tip result = RestTemplateUtils.get(authProperties.getUsersByDeptAndPosition(), uriVariables, Tip.class);
        Assert.isTrue(result.getCode() == SuccessTip.CODE, result.getMessage());
        return JSON.toJavaObject((JSON) result.getContent(), User.class);
    }

    public User getUserByAccount(String account) {
        Map<String, Object> uriVariables = new HashMap<String, Object>();
        uriVariables.put("account", account);
        Tip result = RestTemplateUtils.get(authProperties.getUsersByDeptAndPosition(), uriVariables, Tip.class);
        Assert.isTrue(result.getCode() == SuccessTip.CODE, result.getMessage());
        return JSON.toJavaObject((JSON) result.getContent(), User.class);
    }

    public List<User> getUserByRole(String roleId) {
        Map<String, Object> uriVariables = new HashMap<String, Object>();
        uriVariables.put("roleId", roleId);
        Tip result = RestTemplateUtils.get(authProperties.getUsersByRole(), uriVariables, Tip.class);
        Assert.isTrue(result.getCode() == SuccessTip.CODE, result.getMessage());
        Object content = result.getContent();
        if (content == null) {
            return null;
        }
        return ((List<JSONObject>) content).stream()
                .map(item -> JSON.toJavaObject(item, User.class)).collect(Collectors.toList());
    }
}
